import React, { useState, useEffect, useRef } from 'react';
import { Drawer, List, Button, Typography, Tag, notification, Spin } from 'antd';
import { BookOutlined } from '@ant-design/icons';
import { problemDetailApi } from '../../api/services/Problem/problemDetail';
import type { Problem } from '../../api/vo/problemDetail';
import './ProblemList.less';

const { Title } = Typography;

interface ProblemListProps {
  onSelectProblem: (problem: Problem) => void;
}

const ProblemList: React.FC<ProblemListProps> = ({ onSelectProblem }) => {
  const [visible, setVisible] = useState(false);
  const [problems, setProblems] = useState<Problem[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [hasMore, setHasMore] = useState(true);
  const pageSize = 10;
  const listRef = useRef<HTMLDivElement>(null);
  
  useEffect(() => {
    // 当抽屉打开时获取问题列表
    if (visible) {
      setProblems([]);
      setCurrentPage(1);
      setHasMore(true);
      fetchProblemList(1, true);
    }
  }, [visible]);

  const fetchProblemList = async (page: number, isFirstLoad = false) => {
    if (loading) return;
    
    setLoading(true);
    try {
      const response = await problemDetailApi.getProblemList({
        page,
        size: pageSize
      });
      
      if (response.code === 200) {
        const newProblems = response.data.list;
        const totalCount = response.data.total;
        console.log("newProblems:"+newProblems);
        if (isFirstLoad) {
          setProblems(newProblems);
        } else {
          setProblems(prev => [...prev, ...newProblems]);
        }
        
        setTotal(totalCount);
        setHasMore(page * pageSize < totalCount);
      } else {
        notification.error({
          message: '获取题目列表失败',
          description: response.message
        });
      }
    } catch (error) {
      console.error('获取题目列表失败:', error);
      notification.error({
        message: '获取题目列表失败',
        description: '网络错误，请稍后重试'
      });
    } finally {
      setLoading(false);
    }
  };

  const handleSelectProblem = (problem: Problem) => {
    onSelectProblem(problem);
    setVisible(false);
  };

  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
    
    // 当滚动到底部附近时加载更多数据
    if (scrollHeight - scrollTop <= clientHeight + 50 && hasMore && !loading) {
      const nextPage = currentPage + 1;
      setCurrentPage(nextPage);
      fetchProblemList(nextPage);
    }
  };

  const getDifficultyText = (difficulty: number) => {
    switch (difficulty) {
      case 1:
        return { text: '简单', color: 'green' };
      case 2:
        return { text: '中等', color: 'orange' };
      case 3:
        return { text: '困难', color: 'red' };
      default:
        return { text: '未知', color: 'default' };
    }
  };

  return (
    <>
      <Button
        type="primary"
        icon={<BookOutlined />}
        onClick={() => setVisible(true)}
        style={{ marginLeft: '16px' }}
      >
        题目列表
      </Button>

      <Drawer
        title={<Title level={4} style={{ letterSpacing: '-0.5px' }}>题目列表</Title>}
        placement="left"
        onClose={() => setVisible(false)}
        open={visible}
        width={400}
        className="problem-list-drawer"
        styles={{
          body: { padding: 0, overflow: 'hidden' }
        }}
      >
        <div 
          ref={listRef}
          style={{ height: '100%', overflowY: 'auto', padding: '0 24px' }}
          onScroll={handleScroll}
        >
          <List
            dataSource={problems}
            renderItem={(item, index) => {
              const difficultyInfo = getDifficultyText(item.difficulty);
              const sequenceNumber = index + 1;
              return (
                <List.Item
                  onClick={() => handleSelectProblem(item)}
                  style={{ cursor: 'pointer', padding: '12px 16px' }}
                  actions={[
                    <Tag color={difficultyInfo.color} key="difficulty">
                      {difficultyInfo.text}
                    </Tag>
                  ]}
                >
                  <List.Item.Meta
                    title={<span>{sequenceNumber}. {item.title}</span>}
                    description={
                      item.tags && item.tags.length > 0
                        ? item.tags.map(tag => tag.name).join(' · ')
                        : '暂无标签'
                    }
                  />
                </List.Item>
              );
            }}
          />
          
          {/* 加载更多提示 */}
          {loading && (
            <div style={{ textAlign: 'center', padding: '16px' }}>
              <Spin size="small" /> 加载中...
            </div>
          )}
          
          {!hasMore && total > 0 && (
            <div style={{ textAlign: 'center', padding: '16px', color: '#999' }}>
              已加载全部 {total} 条数据
            </div>
          )}
        </div>
      </Drawer>
    </>
  );
};

export default ProblemList;